package com.yeban.javase.day19.answer.test4;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.LockSupport;

/**
 * @Desc 服务器端的“接话员”，广播消息
 * @Author yeban
 * @Date 2025/11/4
 */
public class ServerTasker implements Runnable {

    private Socket socket;
    private CopyOnWriteArrayList<Socket> clinents;
    private Thread currentThread;
    // 读消息
    BufferedReader br;
    // 写消息
    PrintWriter pw;

    public ServerTasker(Socket socket, CopyOnWriteArrayList<Socket> clinents, Thread currentThread) {
        this.socket = socket;
        this.clinents = clinents;
        this.currentThread = currentThread;
    }

    // 广播消息
    @Override
    public void run() {
        try {
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String msg;
            // 服务端接收消息，并转发至除自己以外的其他客户端
            while((msg = br.readLine()) != null) {
                if(msg.equals("exit")) {
                    // 通知其他客户端下线消息
                    for (Socket client : clinents) {
                        if(client != socket && !client.isClosed()) {
                            pw = new PrintWriter(client.getOutputStream(), true);
                            pw.println(socket.getRemoteSocketAddress() + " 已下线~");
                        }
                    }
                    clinents.remove(socket);
                    break;
                } else {
                    // 转发消息给其他客户端
                    for (Socket client : clinents) {
                        if(client != socket && !client.isClosed()) {    // ？
                            pw = new PrintWriter(client.getOutputStream(), true);
                            pw.println(socket.getRemoteSocketAddress() + "说：" + msg);
                        }
                    }
                    // 同时打印到服务器控制台
                    System.out.println(socket.getRemoteSocketAddress() + " 说: " + msg);
                }
            }
        } catch (SocketException e) {
            System.out.println("客户端异常退出！");
        }  catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            // 释放
            LockSupport.unpark(currentThread);
            if(socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

}
